package com.vogue.supplymall.payment.dto;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

/**
 * 验证DTO属性的基类
 * 
 * @author 崔岳
 *
 */
public abstract class ValidationDTO extends BaseDTO {

	/**
	 * 获取必填字段名字集合
	 * 
	 * @return
	 */
	abstract List<String> requiredFieldList();
	
	/**
	 * 某些字段可选的值，如果不在有效范围内算异常错误
	 * 
	 * @return
	 */
	abstract Map<String, List<Object>> valueValidityMap();
	
	/**
	 * 验证属性有效性的集合
	 * 
	 * @throws Exception
	 */
	public void validationProperty() throws Exception {
		List<String> list = requiredFieldList();
		Map<String, List<Object>> map = valueValidityMap();
		for(Field field : this.getClass().getDeclaredFields()){
            field.setAccessible(true);//把私有属性公有化
            Object object = field.get(this);
            if(list != null && list.contains(field.getName())) {
            	if(object instanceof String){
                    if(object == null || object.toString().equals("")){
                    	throw new Exception(this.getClass() +"->"+field.getName()+"不能为空"); 
                    }
                }else{
                    if(object == null){
                    	throw new Exception(this.getClass() +"->"+field.getName()+"不能为空");
                    }
                }
            }
            
            if(map != null && map.containsKey(field.getName())) {
            	if(!map.get(field.getName()).contains(object)) {
            		throw new Exception(this.getClass() +"->"+field.getName()+"无效的值");
            	}
            }
            
            if(object instanceof List) {
            	for(Object obj : (List)object) {
            		if(obj instanceof ValidationDTO) {
                    	if(!this.equals(obj)) {
                    		((ValidationDTO) obj).validationProperty();
                    	}            	
                    }
            	}
            }else {
            	if(object instanceof ValidationDTO) {
                	if(!this.equals(object)) {
                		((ValidationDTO) object).validationProperty();
                	}            	
                }
            }
        }
	}
}
